package com.aruba.paging4.paging.viewmodel;

import android.os.AsyncTask;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.ViewModel;
import androidx.paging.LivePagedListBuilder;
import androidx.paging.PagedList;

import com.aruba.paging4.database.MyDataBase;
import com.aruba.paging4.entity.Movie;
import com.aruba.paging4.paging.boundarycallback.MovieBoundaryCallback;

/**
 * Created by aruba on 2021/9/17.
 */
public class MovieViewModel extends ViewModel {
    public LiveData<PagedList<Movie>> pagedListLiveData;

    public MovieViewModel() {
//        //配置项
//        PagedList.Config config = new PagedList.Config.Builder()
//                //最大加载多少条数据
//                .setMaxSize(1000 * MovieBoundaryCallback.PER_PAGE)
//                //首次加载多少条数据
//                .setInitialLoadSizeHint(MovieBoundaryCallback.PER_PAGE * 2)
//                //设置距离底部还有多少条数据时开始加载下一页的数据
//                .setPrefetchDistance(2)
//                //一页显示多少条
//                .setPageSize(MovieBoundaryCallback.PER_PAGE)
//                //设置控件占位
//                .setEnablePlaceholders(false)
//                .build();

        //通过Dao获取Factory
        pagedListLiveData = new LivePagedListBuilder<>(
                MyDataBase.getInstance().getMovieDao().getMovieList(),
                MovieBoundaryCallback.PER_PAGE)
                .setBoundaryCallback(new MovieBoundaryCallback())
                .build();
    }

    //刷新数据
    public void refresh() {
        //数据库清空后，会自动重新加载
        new AsyncTask<Void, Void, Void>() {

            @Override
            protected Void doInBackground(Void... voids) {
                MyDataBase.getInstance().getMovieDao().clear();
                return null;
            }
        }.execute();
    }
}
